﻿//承运商管理
/**
 * fixed by zhaojian
 */
interface ICarrierManagentViewModel extends IBaseViewModel<ICarrierManagentQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<CarrierListItemResponse>;
    /**
     * 承运商类型下拉
     */
    carrierTypeDropDown: ValueListItemResponse[];
    /**
     * 承运商等级下拉
     */
    carrierLevelDropDown: ValueListItemResponse[];
    /**
     * 查询
     */
    query: () => void;
    /**
     * 删除承运商
     */
    deleteCarrier: (id: string) => void;
    /**
     * 启用/禁用承运商
     */
    disenableCarrier: (isEnable: boolean, id: string) => void;
    /**
     * 批量禁用
     */
    batchDisabledCarrier: () => void;
    /**
     * 批量启用
     */
    batchEnabledCarrier: () => void;
    /**
     * 翻页后选中
     */
    resumeSelectedItem: () => void;
    /**
     * 导出
     */
    export: () => void;
    /**
     * 列表高度
     */
    heightA: number;
}

interface CarrierListData {
    /**
     * id
     */
    id: string;
    /**
     * 启用、禁用
     */
    isEnabled: boolean
}

/**
 * 查询条件
 */
interface ICarrierManagentQueryTerms {
    /**
     * 承运商名称
     */
    name: string;
    /**
     * 承运商类型
     */
    type: string;
    /**
     * 承运商号码
     */
    phone: string;
    /**
     * 录入人
     */
    inputPerson: string;
    /**
     * 承运商等级
     */
    level: string;
    /**
     * 主营路线
     */
    mainRoute: string;
    /**
     * 是否启用
     */
    isEnabled: boolean;
}

class CarrierManagentController extends ListController<ICarrierManagentViewModel, ICarrierManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<CarrierListItemResponse>;
    /**
     * 已选承运商，在重新查询后会清除
     */
    selectedCarrierIds: CarrierListData[];
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean = false;
    orderBy: number = 0;
    asc: boolean = true;
    skip:number = 0;


    carrierDataList: Array<CarrierListItemResponse>;

    constructor($scope: ICarrierManagentViewModel, private carrierService: ICarrierService, private routeService: routeService,
        private valueService: IValueService, private $ngBootbox: BootboxService, private $state: angular.ui.IStateService, private $timeout: ng.ITimeoutService,
        private exportService: IexportService,private $location:ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.$scope.deleteCarrier = this.deleteCarrier;
        this.$scope.disenableCarrier = this.disenableCarrier;
        this.$scope.batchDisabledCarrier = this.batchDisabledCarrier;
        this.$scope.batchEnabledCarrier = this.batchEnabledCarrier;
        //this.$scope.export=this.excel;

        this.$scope.queryTerms = {
            name: "",
            type: "",
            phone: "",
            inputPerson: "",
            level: "",
            mainRoute: "",
            isEnabled: null
        };

        this.$scope.gridOptions = {

            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableFullRowSelection: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "承运商序号", field: 'index', enableColumnMenu: false, width: 88, enableSorting: false },
                { displayName: "承运商类型", field: 'type', enableColumnMenu: false },
                { displayName: "承运商名称", field: 'name', enableColumnMenu: false },
                { displayName: '承运商号码', field: 'phone', enableColumnMenu: false },
                { displayName: '主营路线', field: 'mainRoute', enableColumnMenu: false, enableSorting: false, minWidth: 150, },
                { displayName: '承运商等级', field: 'level', enableColumnMenu: false },
                { displayName: '录入人', field: 'inputPerson', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ui-sref="app.carrier.carrierManagentEdit({id:row.entity.id,name:\'carrierManagentEdit\'})"></a> <a class="primary fa fa-trash-o text-danger" title="删除" ng-click="grid.appScope.deleteCarrier(row.entity.id)"></a>'
                    + '<a class="fa fa-check-circle primary text-success m-l-xs" ng-click="grid.appScope.disenableCarrier(row.entity.isEnabled,row.entity.id)" title="启用" ng-hide="row.entity.isEnabled"></a>'
                    + '<a class="fa fa-minus-circle primary text-primary m-l-xs" ng-show="row.entity.isEnabled" title="禁用" ng-click="grid.appScope.disenableCarrier(row.entity.isEnabled,row.entity.id)"></a>',
                    enableColumnMenu: false, enableSorting: false
                }],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
                gridApi.selection.on.rowSelectionChangedBatch(this.$scope, this.batchSelectChange);
            }
        }

        this.$scope.query = this.query;
        this.query();
        this.loadCarrierTypeDropDown();
        this.loadCarrierLevelDropDown();
    }

    loadData(queryTerms: ICarrierManagentQueryTerms, skip: number, count: number): void {
        this.carrierService.getList(this.orderBy.toString(), this.asc, queryTerms.name, queryTerms.phone, queryTerms.type, queryTerms.inputPerson, queryTerms.level, queryTerms.mainRoute, queryTerms.isEnabled, skip, count).then(result => {
            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.skip = skip;

            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ +1);
            // console.log(this.$scope.gridOptions.paginationCurrentPage);
            this.$scope.gridOptions.data = result.data.data;
            /**
             * 设置列表高度
             */
            this.$scope.heightA = ((result.data.data.length) * 39) + 96;

            this.resumeSelectedItem(this.$scope.gridOptions.data);
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        })
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    onQuery(): void {
        super.onQuery();
        this.selectedCarrierIds = [];
    }

    /**
     * 下拉承运商类别事件
     */
    loadCarrierTypeDropDown = () => {
        this.$scope.carrierTypeDropDown = this.valueService.getCarrierTypeList().data
    }

    /**
     * 下拉承运商级别事件
     */
    loadCarrierLevelDropDown = () => {
        this.$scope.carrierLevelDropDown = this.valueService.getCarrierLevelList().data
    }

    /**
     * 排序事件触发
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<CarrierListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<CarrierListItemResponse>>) => {
        if (sortColumns.length == 0) {
            this.query();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "type": {
                    this.orderBy = 2;
                } break;
                case "name": {
                    this.orderBy = 3;
                } break;
                case "phone": {
                    this.orderBy = 4;
                } break;
                case "level": {
                    this.orderBy = 5;
                } break;
                case "inputPerson": {
                    this.orderBy = 6;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.query();
        }
    }

    /**
     * 单选事件
     */
    selectChange = (row: uiGrid.IGridRowOf<CarrierListItemResponse>) => {
        if (this.lockSelect) {
            return;
        }

        if (row.isSelected == true) {
            this.selectedCarrierIds.forEach((item, index) => {
                if (row.entity.id == item.id) {
                    this.selectedCarrierIds.splice(index, 1);
                }
            })
            this.selectedCarrierIds.push({
                id: row.entity.id,
                isEnabled: row.entity.isEnabled
            });
        } else {
            this.selectedCarrierIds.forEach((item, index) => {
                if (row.entity.id == item.id) {
                    this.selectedCarrierIds.splice(index, 1);
                }
            });
        }
    }

    /**
     * 全选事件
     */
    batchSelectChange = (rows: Array<uiGrid.IGridRowOf<CarrierListItemResponse>>) => {
        if (this.lockSelect) {
            return;
        }

        rows.forEach((item, index) => {
            if (item.isSelected) {
                this.selectedCarrierIds.push({
                    id: item.entity.id,
                    isEnabled: item.entity.isEnabled
                });
            } else {
                rows.forEach((item, index) => {
                    this.selectedCarrierIds.forEach((items, indexs) => {
                        if (item.entity.id === items.id) {
                            this.selectedCarrierIds.splice(indexs, 1);
                        }
                    });
                });
            }
        });
    }

    /**
     * 恢复选中
     */
    resumeSelectedItem(data: string | CarrierListItemResponse[]): void {
        if (this.selectedCarrierIds.length <= 0) {
            return;
        }
        // this.lockSelect = true;
        if (this.isCarrierListItemResponse(data)) {
            data.forEach((item, index) => {
                this.selectedCarrierIds.forEach((itemS, indexS) => {
                    if (item.id === itemS.id) {
                        this.$timeout(() => {
                            if (this.isCarrierListItemResponse(data)) {
                                this.gridApi.selection.selectRow(data[index]);
                                console.log(this.selectedCarrierIds)
                            }
                        });
                    }
                });
            });
        }
        this.lockSelect = false;
    }


    isCarrierListItemResponse(response: string | CarrierListItemResponse[]): response is CarrierListItemResponse[] {
        return (<CarrierListItemResponse[]>response).forEach !== undefined;
    }

    /**
     * 删除承运商
     */
    deleteCarrier = (id: string) => {
        this.$ngBootbox.confirm("是否删除该数据").then(e => {
            this.carrierService.delete(id).then(e => {
                this.reload();
            })
        })
    }

    /**
     * 启用或禁用承运商
     */
    disenableCarrier = (isEnabled: boolean, id: string) => {
        this.carrierService.enabled(!isEnabled, id).then(result => {
            this.reload();
        });
    }

    /**
     * 根据selectedCarrierIds批量禁用
     */
    batchDisabledCarrier = () => {
        if (this.selectedCarrierIds.length < 1) {
            this.$ngBootbox.alert("请至少选择一条数据");
            return;
        }

        var yes = true;
        this.selectedCarrierIds.forEach((item, index) => {
            if (item.isEnabled == false) {
                yes = false;
                return false;
            };
        });
        //    var yes = this.selectedCarIds.every(this.isEnabledPass);      
        if (!yes) {
            this.$ngBootbox.alert("承运商不是启用状态,不能禁用");
            return;
        }
        var idArr = [];
        this.selectedCarrierIds.forEach((item, index) => {
            idArr.push(item.id);
        });


        this.carrierService.enabled(false, idArr.join(",")).then(result => {
            this.selectedCarrierIds = [];
            this.gridApi.selection.clearSelectedRows();
            this.reload();
        });
    }

    /**
     * 根据selectedCarrierIds批量启用
     */
    batchEnabledCarrier = () => {
        if (this.selectedCarrierIds.length < 1) {
            this.$ngBootbox.alert("请至少选择一条数据");
            return;
        }
        var yes = true;
        this.selectedCarrierIds.forEach((item, index) => {
            if (item.isEnabled == true) {
                yes = false;
                return false;
            };
        });

        if (yes) {
            var idArr = [];
            this.selectedCarrierIds.forEach((item, index) => {
                idArr.push(item.id);
            });
        } else {
            this.$ngBootbox.alert("承运商不是禁用状态,不能启用");
            return;
        }

        this.carrierService.enabled(true, idArr.join(",")).then(result => {
            this.selectedCarrierIds = [];
            this.gridApi.selection.clearSelectedRows();
            this.reload();
        });
    }
    //导出优化
    exportFunc = () => {
        if(this.$scope.gridOptions.totalItems>30000){
            this.$ngBootbox.alert('导出数据不可超过3万条');
            return;
        }else{
            this.exportService.exportCarrierList(this.orderBy, this.asc, encodeURIComponent(this.$scope.queryTerms.name), this.$scope.queryTerms.phone, this.$scope.queryTerms.type, this.$scope.queryTerms.inputPerson, this.$scope.queryTerms.level, this.$scope.queryTerms.mainRoute, this.$scope.queryTerms.isEnabled, 0, -1);
        }      
    }

}

angular.module("tms").controller("carrierManagentController", ["$scope", "carrierService", "routeService", "valueService", "$ngBootbox", "$state", "$timeout", "exportService","$location", CarrierManagentController]);
